<?php

require_once(dirname(__FILE__) . '/Connector.class.php');
require_once(dirname(__FILE__) . '/Logger.class.php');

/**
 * Curl implementation of the Connector interface.
 */

$HTTP_HEADER = array();
function extractHeaders($curl, $header) {
	global $HTTP_HEADER;
	if (empty($header)) {
		return 0;
	}
	
	if (strpos($header, ':') === FALSE) {
		// Probably HTTP header
		return strlen($header);
	}
	
	$key = strtolower(trim(substr($header, 0, strpos($header, ':'))));
	$val = trim(substr($header, strpos($header, ':') + 1));
	
	if (array_key_exists($key, $HTTP_HEADER)) {
		if (is_array($HTTP_HEADER)) {
			$HTTP_HEADER[$key][] = $val;
		}
		else {
			$HTTP_HEADER[$key] = array($HTTP_HEADER[$key], $val);
		}
	}
	else {
		$HTTP_HEADER[$key] = $val;
	}
	
	//$this->log->debug('Set header: ' . $key . ' => ' . $val);
	
	return strlen($header);
}
/**
 * Callback function -- cURL will callback this function with the body.
 */
$HTTP_BODY;
function extractBody($curl, $body) {
	global $HTTP_BODY;
	// if ($this->callbackHeaders === FALSE) {
	// 	$this->buffer = $this->proxy->handleHeaders($this->headers);
	// 	$this->callbackHeaders = TRUE;
	// }
	
	// if (empty($body)) {
	// 	return 0;
	// }
	
	// if ($this->buffer) {
	// 	$this->output .= $body;
	// }
	//else {
		$HTTP_BODY = $body;
	//}
	
	return strlen($body);
}


function get($url){
	$url ='https://images-onepick-opensocial.googleusercontent.com/gadgets/proxy?container=onepick&gadget=a&rewriteMime=image%2F*&url='.encodeURIComponent($url);
	//$url = 'https://images-onepick-opensocial.googleusercontent.com/gadgets/proxy?container=main&url='.encodeURIComponent($url);
	$proxy = 'internet.tri.co.id:80';
	//$proxyauth = 'user:password';

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_PROXY, $proxy);
	//curl_setopt($ch, CURLOPT_PROXYUSERPWD, $proxyauth);
	curl_setopt($ch, CURLOPT_HEADER, 0); // return headers 0 no 1 yes
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // return page 1:yes
	curl_setopt($ch, CURLOPT_TIMEOUT, 300); // http request timeout 20 seconds
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Follow redirects, need this if the url changes
	curl_setopt($ch, CURLOPT_MAXREDIRS, 2); //if http server gives redirection responce
	curl_setopt($ch, CURLOPT_USERAGENT,'Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30');//"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7");
	//curl_setopt($ch, CURLOPT_HEADER, 1);
	curl_setopt($ch, CURLOPT_COOKIEJAR, "cookies.txt"); // cookies storage / here the changes have been made
	curl_setopt($ch, CURLOPT_COOKIEFILE, "cookies.txt");
	curl_setopt($ch, CURLOPT_FOLLOWLOCATION, FALSE);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
	curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
	curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // Disable SSL cert checking
	curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // cURL does not like some SSL certs apparently
	curl_setopt($ch, CURLOPT_HEADERFUNCTION, 'extractHeaders');
	//curl_setopt($ch, CURLOPT_WRITEFUNCTION, 'extractBody');
	return $ch;
}
class CurlConnector implements Connector {
	
	var $headers = array();
	
	function __construct($proxy, $url) {
		$this->log = new Logger();
		$this->url = $url;
		$this->proxy = $proxy;
		$this->callbackHeaders = FALSE;
		$this->buffer = TRUE;
		
		$this->curl = curl_init($this->url);
		

		$this->log->debug('Sending user agent: ' . $_SERVER['HTTP_USER_AGENT']);
		
		$httpp="internet.tri.co.id:8888";

		curl_setopt($this->curl, CURLOPT_PROXY, $httpp);
		curl_setopt($this->curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
		curl_setopt($this->curl, CURLOPT_FOLLOWLOCATION, FALSE);
		curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($this->curl, CURLOPT_AUTOREFERER, TRUE);
		curl_setopt($this->curl, CURLOPT_SSL_VERIFYPEER, FALSE); // Disable SSL cert checking
		curl_setopt($this->curl, CURLOPT_SSL_VERIFYHOST, FALSE); // cURL does not like some SSL certs apparently
		curl_setopt($this->curl, CURLOPT_HEADERFUNCTION, array(&$this, 'extractHeaders'));
		curl_setopt($this->curl, CURLOPT_WRITEFUNCTION, array(&$this, 'extractBody'));
		
		$this->log->debug('Curl Connector initialised with URL: ' . $this->url);
	}
	
	function setLogin($username, $password) {
		$this->username = $username;
		$this->password = $password;
		
		curl_setopt($this->curl, CURLOPT_USERPWD, $this->username . ':' . $this->password);
	}
	
	function setPostInfo($fields) {
		$postdata = '';
		$fileUpload = FALSE;
		
		foreach($fields as $key=>$val) {
			if (substr($val, 0, 1) == '@') {
				$fileUpload = TRUE;
				break;
			}
			
			$postdata .= urlencode($key) . '=' . urlencode($val);
			$postdata .= '&';
		}
		
		curl_setopt($this->curl, CURLOPT_POST, TRUE);
		curl_setopt($this->curl, CURLOPT_POSTFIELDS, $fileUpload == TRUE ? $fields : $postdata);
	}
	
	function setReferer($referer) {
		//curl_setopt($this->curl, CURLOPT_REFERER, $url);
	}
	
	function setCookie($cookie) {
		curl_setopt($this->curl, CURLOPT_COOKIE, $cookie);
	}
	
	function connect() {
		
		global $HTTP_HEADER;
		//print_r($result);
		//$this->output = $result;
		$pinfo = pathinfo($this->url);
		//print_r($pinfo);
		$mime = false;
		if(!empty($pinfo['extension']))
		{
			$mime = getMime($pinfo['extension']);
			
		}
		
		$ext = $pinfo['extension'];


		$ext = $ext? $ext:'html';
		// if($ext != 'html')
		// 	die($mime);

		$filename = 'tmp/tmp'.md5($this->url).('.'.$ext);
		
		//if(!file_exists($filename) || filesize($filename) <= 0)
		//{
			$curl = get($this->url);
			$result = curl_exec($curl);
			
			touch($filename);
			file_put_contents($filename, $result);
		//}
		//else
		//{
			$info['http_code'] = 200;
		//}
		
		//die($this->url);
		$result = 1;
		if(!$mime){
			$finfo = finfo_open(FILEINFO_MIME_TYPE);
			$mime = finfo_file($finfo, $filename);
			//die($mime);
			finfo_close($finfo);
		}
		$this->headers['content-type'] = $mime;
		//die($mime);
		
		if ($result === FALSE) {
			$this->log->error(sprintf('Error [%d] connecting to URL. Error was: %s', curl_errno($this->curl), curl_error($this->curl)));
			return FALSE;
		}
		
		$info = curl_getinfo($curl);

		
		header('Content-Type: '.$mime);
		$this->httpCode = $info['http_code'];
		//
		if ($this->callbackHeaders === FALSE) {
			//print_r($info);

			//$this->proxy->handleHeaders($HTTP_HEADER);
			$this->callbackHeaders = TRUE;
		}
		

		$this->output .= file_get_contents($filename);
		if(in_array($ext, array('png','gif','jpg','jpeg','ico')))
			echo($this->output);
		// if ($this->callbackHeaders === FALSE) {
		// 	$this->buffer = $this->proxy->handleHeaders($HTTP_HEADER);
		// 	$this->callbackHeaders = TRUE;
		// }
		
		// if (! empty($HTTP_BODY)) {
		// 	return 0;
		
		
		// 	if ($this->buffer) {
		// 		$this->output .= $HTTP_BODY;
		// 	}
		// }
		// return TRUE;
	}
	
	function disconnect() {
		curl_close($this->curl);
	}
	
	function getError() {
		return curl_error($this->curl);
	}
	
	function getHeaders() {
		return $this->headers;
	}
	
	function getHttpCode() {
		return $this->httpCode;
	}
	
	function getOutput() {
		return $this->output;
	}
	
	/** 
	 * Callback function -- cURL will callback this function with each header.
	 */
	function extractHeaders($curl, $header) {
		if (empty($header)) {
			return 0;
		}
		
		if (strpos($header, ':') === FALSE) {
			// Probably HTTP header
			return strlen($header);
		}
		
		$key = strtolower(trim(substr($header, 0, strpos($header, ':'))));
		$val = trim(substr($header, strpos($header, ':') + 1));
		
		if (array_key_exists($key, $this->headers)) {
			if (is_array($this->headers[$key])) {
				$this->headers[$key][] = $val;
			}
			else {
				$this->headers[$key] = array($this->headers[$key], $val);
			}
		}
		else {
			$this->headers[$key] = $val;
		}
		
		$this->log->debug('Set header: ' . $key . ' => ' . $val);
		
		return strlen($header);
	}
	
	/**
	 * Callback function -- cURL will callback this function with the body.
	 */
	function extractBody($curl, $body) {
		if ($this->callbackHeaders === FALSE) {
			$this->buffer = $this->proxy->handleHeaders($HTTP_HEADER);
			$this->callbackHeaders = TRUE;
		}
		
		if (empty($body)) {
			return 0;
		}
		
		if ($this->buffer) {
			$this->output .= $body;
		}
		else {
			echo $body;
		}
		
		return strlen($body);
	}
}